package com.dg11185.nearshop.activity.home.actys;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import org.apache.http.Header;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.AsyncHttpResponseHandler;
import com.dg11185.libs.ormlite.android.apptools.OpenHelperManager;
import com.dg11185.libs.ormlite.dao.Dao;
import com.dg11185.libs.ormlite.stmt.UpdateBuilder;
import com.dg11185.libs.utils.date.DateUtils;
import com.dg11185.libs.utils.print.PrintUtils;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.app.ViewUtils;
import com.dg11185.nearshop.dbHelper.OrmLiteHelper;
import com.dg11185.nearshop.net.response.NetStatus;
import com.dg11185.nearshop.net.weixin.Tabloid;
import com.dg11185.nearshop.net.weixin.TabloidRequest;
import com.dg11185.nearshop.net.weixin.TabloidResponse;
import com.wlper.lib.view.loading.LoadLayoutWithTweenAnim;

/**
 * 小报消息界面
 * 
 * @author：Daibo
 * @time：2014-9-4 下午4:37:07
 */
public class TabloidActivity extends SubPageActivity {

    private static final int LOAD_MIAN = 0;

    private static final int LOAD_MORE = 1;

    private static final int LOAD_FREE = 2;

    private int loadState = LOAD_FREE;

    //判断服务器的小报消息是否加载完毕
    private boolean isLoadOver = false;
    
    private LoadLayoutWithTweenAnim loadingView = null;

    private ListView listView = null;

    private TabloidAdapter adapter = null;

    private List<Tabloid> tabloids = null;

    private View listHeadView = null;

    /** 数据库 */
    private OrmLiteHelper databaseHelper = null;// 底包数据库helper

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabloid_main);
        loadingView = (LoadLayoutWithTweenAnim) findViewById(R.id.tabloid_loading);
        listView = (ListView) this.findViewById(R.id.tabloid_list);

        listHeadView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.tabloid_load_view, null);
        listHeadView.setVisibility(View.GONE);
        listView.addHeaderView(listHeadView);

        adapter = new TabloidAdapter(this);
        listView.setAdapter(adapter);

        try {
            Dao<Tabloid, Integer> tabloidDao = getHelper().getTabloidDao();
            tabloids = tabloidDao.queryForAll();
            if (tabloids != null && tabloids.size() > 0) {

                if (tabloids.size() > 50) {
                    // 数据库数据条数大于50，删除50条之后的数据
                    List<Tabloid> temps = tabloids.subList(0, tabloids.size() - 50);
                    tabloidDao.delete(temps);
                }
                PrintUtils.printc(tabloids);
                
                UpdateBuilder<Tabloid, Integer> updateBuilder = tabloidDao.updateBuilder();
                updateBuilder.updateColumnValue("isReaded", true);
                updateBuilder.update();

                PrintUtils.printc(tabloidDao.queryForAll());
                adapter.setTabloids(tabloids);
                adapter.notifyDataSetChanged();
                listView.setSelection(adapter.getCount());
                listView.setOnScrollListener(scrollListener);
            } else {

                String stTime = DateUtils.dayMove(DateUtils.getCurrentDate(), -60);
                TabloidRequest request = new TabloidRequest(stTime, "1");
                loadState = LOAD_MIAN;
                NetClient.client.get(TabloidActivity.this, request.getUrl(), netHandler);
                System.out.println(request.getUrl());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        NetClient.httpCancel(this, true);
        /*
         * You'll need this in your class to release the helper when done.
         */
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }
        super.onDestroy();
    }

    /**
     * You'll need this in your class to get the helper from the manager once
     * per class.
     */
    public OrmLiteHelper getHelper() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(mActivity, OrmLiteHelper.class);
        }
        return databaseHelper;
    }

    /**
     */
    private AsyncHttpResponseHandler netHandler = new AsyncHttpResponseHandler() {
        public void onStart() {
            if (loadState == LOAD_MIAN) {
                loadingView.onLoading();
            } else if (loadState == LOAD_MORE) {
                listHeadView.setVisibility(View.VISIBLE);
            }
        };

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            TabloidResponse result = new TabloidResponse();
            result.parseJson(new String(responseBody));
            if (result.status == NetStatus.SUCCESS) {
                if (result.tabloids.size() > 0) {
                    loadingView.onLoadSuccess();
                    if (tabloids == null) {
                        Collections.reverse(result.tabloids);
                        tabloids = result.tabloids;
                    } else {
                        Collections.reverse(result.tabloids);
                        tabloids.addAll(0, result.tabloids);
                    }
                    adapter.notifyDataSetChanged();
                    listView.setSelection(result.tabloids.size());
                } else {
                    onFailure(statusCode, headers, responseBody, null);
                }
            } else if (result.status == NetStatus.EMPTY_DATA) {
                isLoadOver = true;
                ViewUtils.showToast(TabloidActivity.this, "没有更多数据了..");
            } else {
                onFailure(statusCode, headers, responseBody, null);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            if (loadState == LOAD_MIAN) {
                loadingView.onLoadFailed();
            }
        }

        public void onFinish() {
            loadState = LOAD_FREE;
            listHeadView.setVisibility(View.GONE);
        };
    };

    /**
     * Listview 滑动到顶部加载新数据
     */
    private OnScrollListener scrollListener = new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
            case OnScrollListener.SCROLL_STATE_IDLE:
                if (listView.getLastVisiblePosition() == adapter.getCount() - 1) {

                } else if (listView.getFirstVisiblePosition() == 0) {
                    if (loadState == LOAD_FREE && isLoadOver == false) {
                        TabloidRequest request = new TabloidRequest(getOldestTime(), "1");
                        NetClient.client.get(TabloidActivity.this, request.getUrl(), netHandler);
                        listHeadView.setVisibility(View.VISIBLE);
                        loadState = LOAD_MORE;
                    }
                }
                break;

            case OnScrollListener.SCROLL_STATE_FLING:
                break;
            default:
                break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    };

    private String getOldestTime() {
        String time = null;

        for (Tabloid t : tabloids) {
            if (time != null) {
                long disTime = DateUtils.getMinutesBetween(time, t.createTime);
                if (disTime > 0) {
                    time = t.createTime;
                }
            } else {
                time = t.createTime;
            }
        }
        return time;
    }
}
